package com.qdsg.modulesihealsdk.ecgSingle.recvdata;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.creative.base.BaseDate.ECGData;
import com.creative.base.BaseDate.Wave;
import com.creative.base.InputStreamReader;
import com.creative.base.OutputStreamSender;
import com.creative.ecg.ECG;
import com.creative.ecg.IECGCallBack;
import com.creative.ecg.StatusMsg;
import com.creative.filemanage.ECGFile;
import com.creative.filemanage.FileOperation;
import com.qdsg.modulesihealsdk.ecgSingle.tool.MyUtil;
import com.qdsg.modulesihealsdk.entity.ECGRecord;
import com.qdsg.modulesihealsdk.utils.SihealSdkConstant;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;

public class StaticReceive implements Serializable {
	private final String TAG = "StaticReceive";
	
	/**
	 * PC80B系列协议解析
	 * analyse PC80B protocal 
	 */
	private ECG ecg;

	/**
	 * 通知上层各种数据消息
	 * updata UI handler
	 */
	private Handler mHandler;

	/** buffer of saving wave ,write to file */
	public List<Wave> mWaveBuffer = new ArrayList<Wave>();

//----------- save wave ----

	public ECGRecord ecgRecord = new ECGRecord();

	public boolean pause = false;

	public boolean start = false;

	/**
	 * 保存ECG波形数据,用于绘制波形
	 * save for drawing wave of ECG
	 */
	public List<Wave> DRAWDATA = new ArrayList<Wave>();

	/**
	 * 开始接收数据
	 * start to receive data
	 * @param bluName
	 */
	public void startReceive(String bluName, InputStreamReader iReader, OutputStreamSender iSender, Handler _handler) {
		if (bluName != null && !bluName.equals("")) {
			start = true;
			mHandler = _handler;
			//mContext = context;
			 if(bluName.contains("PC80B")){
				ecg = new ECG(iReader, iSender, new ECGCallBack());
				ecg.Start();
				ecg.QueryDeviceVer();
				
			}
		}
	}

	/**
	 * 停止接收数据
	 * stop receiving data
	 */
	public void StopReceive() {
		start = false;
		if (ecg != null) {
			ecg.Stop();
			ecg = null;
		}
	}

	/**
	 * 暂停数据接收
	 * pause receiving data
	 */
	public void Pause() {
		pause = true;
		if (ecg != null) {
			ecg.Pause();
		}
	}

	/**
	 *  恢复数据接收
	 *  recover receiving data
	 */
	public void Continue() {
		pause = false;
		if (ecg != null) {
			ecg.Continue();
		}
	}

	public void setmHandler(Handler mHandler) {
		this.mHandler = mHandler;
	}



	private class ECGCallBack implements IECGCallBack {
		@Override
		public void OnConnectLose() {
			Log.d("TAG", "-->bluetooth disconnect..");
			mHandler.sendEmptyMessage(SihealSdkConstant.MSG_TERMINAL_OFFLINE );
		}

		@Override
		public void OnGetDeviceVer(String hardVer,String softVer,String algorithmVer) {
			System.out.println("hardVer:"+hardVer+",softVer:"+softVer+",algorithmVer:"+algorithmVer);		
		}

		//终端应答有响应：每隔1秒发送心跳报文,电量信息.
		// terminal responsed, send powerInfo per-second 
		@Override
		public void OnGetPower(int nPower) {
			mHandler.obtainMessage(SihealSdkConstant.MSG_DATA_BATTERY, nPower, 0).sendToTarget();
		}

		@Override
		public void OnGetRealTimeResult(String time, int nTransMode,
				int nResult, int nHR) {
			Message msg = mHandler.obtainMessage();
			msg.what = SihealSdkConstant.MSG_DATA_ECG_STATUS_CH;
			msg.arg1 = 6;//result msg
			Bundle data = new Bundle();
			data.putInt("nTransMode", nTransMode);
			data.putInt("nResult", nResult);
			data.putInt("nHR", nHR);
			data.putString("time", time);
			msg.setData(data);
			mHandler.sendMessage(msg);
			ecgRecord.setResultCode(nResult);
			ecgRecord.setAvgHR(nHR);
			writeWave2File(nResult,nHR);
		}

		@Override//pc80b: 4500 point = 180* 25
		public void OnGetRealTimeMeasure(boolean bLeadoff, ECGData ecgData, int nTransMode, 
				int nHR, int nPower, int nGain) {
			Message msg = mHandler.obtainMessage();
			msg.what = SihealSdkConstant.MSG_DATA_ECG_STATUS_CH;
			msg.arg1 = 5;
			Bundle data = new Bundle();
			data.putBoolean("bLeadoff", bLeadoff);
			data.putInt("nTransMode", nTransMode);
			data.putInt("nHR", nHR);
			data.putInt("nPower", nPower);
			data.putInt("nGain", nGain);
			msg.setData(data);
			ecgRecord.setGain(nGain);
			
			mHandler.sendMessage(msg);
			// buffer wave for drawing
			DRAWDATA.addAll(ecgData.data); //ecgData.data.size() = 25
			//Log.d("TAG","wave data->"+arg1.data);		
			mWaveBuffer.addAll(ecgData.data); //total of realTime wave are 4500 point 
		}

		@Override//pc80b: 2250 point
		public void OnGetRealTimePrepare(boolean bLeadoff, ECGData ecgData, int nGain) {
			Message msg = mHandler.obtainMessage();
			msg.what = SihealSdkConstant.MSG_DATA_ECG_STATUS_CH;
			msg.arg1 = 4;
			Bundle data = new Bundle();
			data.putBoolean("bLeadoff", bLeadoff);
			data.putInt("nGain", nGain);
			DRAWDATA.addAll(ecgData.data); //ecgData.data.size() = 25
			msg.setData(data);
			mHandler.sendMessage(msg);	
		}

		@Override
		public void OnGetRequest(String sDeviceID, String sProductID,
				int nSmoothingMode, int nTransMode) {
			mHandler.obtainMessage(SihealSdkConstant.MSG_DATA_ECG_STATUS_CH, 7, nSmoothingMode,
					nTransMode).sendToTarget();
		}

		//status: file transfer status
		@Override 
		public void OnGetFileTransmit(int status, Vector<Integer> scpSrc) {
			System.out.println("OnGetFileTransmit status:" + status);
			if(status == StatusMsg.FILE_TRANSMIT_SUCCESS){
				try {
					ECGFile ecg = FileOperation.AnalyseSCPFile(scpSrc);
					List<Integer> yList = ecg.ecgData;// all wave high for Y axis
//					int result = ecg.nAnalysis; //ECG analyse result
//					int waveGain = ecg.nGain;
//					String time = ecg.time;
//					int heartRate = ecg.nAverageHR;
//					int smoothingMode = ecg.nSmoothingMode;
					Log.d(TAG, Arrays.toString(yList.toArray()));
					Log.e(TAG, ecg.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			mHandler.obtainMessage(SihealSdkConstant.MSG_DATA_ECG_STATUS_CH, status, 0, scpSrc).sendToTarget();
		}

		@Override
		public void OnReceiveTimeOut(int code) {
			//System.out.println("OnReceiveTimeOut code:"+code);
			mHandler.obtainMessage(SihealSdkConstant.MSG_DATA_ECG_STATUS_CH, SihealSdkConstant.MSG_DATA_TIMEOUT, 0,
					0).sendToTarget();
		}

		@Override
		public void OnGetFileProgress(int progress) {//166
			//Log.d(TAG, "progress:"+progress);
			mHandler.obtainMessage(SihealSdkConstant.MSG_DATA_ECG_STATUS_CH, 8, progress).sendToTarget();
		}
	}


	public void writeWave2File(int nResult,int nHR){
		new Thread(){
			@Override
			public void run() {
/******************  .ECG *******************/
				List<Integer> datas = new ArrayList<Integer>();
				while (mWaveBuffer.size()>0) {
					Wave wave = mWaveBuffer.remove(0);
					datas.add(wave.data);//存放波形Y轴数据, Y axis of wave 
				}			
				MyUtil.writeFile(SihealSdkConstant.filePath, SihealSdkConstant.fileName, datas,ecgRecord,nResult,nHR);
	
/******************  .SCP *******************/
//				int[] ecg_dat = new int[4500];
//				for (int j=0;j<ecg_dat.length;j++) {
//					Wave wave = mWaveBuffer.remove(0);
//					ecg_dat[j] = wave.data;//存放波形Y轴数据, Y axis of wave 
//				}
//				//Log.d("TAG", "write size:"+datas.size());
//				SCPFile scpFile = new SCPFile(filePath,ecg_dat);
//				scpFile.packSCP();						
			};	
		}.start();
	}
		
}
